from django import template
import math

register = template.Library()


# 基础数学运算
@register.filter(name='subtract')
def subtract(value, arg):
    """减法过滤器"""
    try:
        return value - int(arg)
    except (ValueError, TypeError):
        return value


@register.filter(name='add')
def add(value, arg):
    """加法过滤器"""
    try:
        return value + int(arg)
    except (ValueError, TypeError):
        return value


@register.filter(name='multiply')
def multiply(value, arg):
    """乘法过滤器"""
    try:
        return value * float(arg)
    except (ValueError, TypeError):
        return value


@register.filter(name='divide')
def divide(value, arg):
    """除法过滤器"""
    try:
        return value / float(arg)
    except (ValueError, ZeroDivisionError, TypeError):
        return 0


@register.filter(name='modulo')
def modulo(value, arg):
    """取模过滤器"""
    try:
        return value % int(arg)
    except (ValueError, ZeroDivisionError, TypeError):
        return value


# 数学函数
@register.filter(name='floor')
def floor(value):
    """向下取整"""
    try:
        return math.floor(value)
    except (ValueError, TypeError):
        return value


@register.filter(name='ceil')
def ceil(value):
    """向上取整"""
    try:
        return math.ceil(value)
    except (ValueError, TypeError):
        return value


# 比较函数
@register.filter(name='min_filter')
def min_filter(value, arg):
    """最小值过滤器（避免与内置min冲突）"""
    try:
        return min(value, arg)
    except TypeError:
        return value


@register.filter(name='max_filter')
def max_filter(value, arg):
    """最大值过滤器（避免与内置max冲突）"""
    try:
        return max(value, arg)
    except TypeError:
        return value


# 实用函数
@register.filter(name='range_filter')
def range_filter(start, end=None):
    """生成范围过滤器"""
    try:
        if end is None:
            return []
        start = int(start)
        end = int(end)
        return list(range(start, end + 1))
    except (ValueError, TypeError):
        return []


@register.filter(name='format_number')
def format_number(value):
    """格式化数字（添加千位分隔符）"""
    try:
        return f"{value:,}"
    except (ValueError, TypeError):
        return value


# 分页专用函数
@register.filter(name='half_visible')
def half_visible(value):
    """计算一半可见页码数"""
    try:
        return max(1, math.floor(value / 2))
    except (ValueError, TypeError):
        return 1


@register.filter(name='calculate_start')
def calculate_start(page_number, half):
    """计算起始页码"""
    try:
        return max(1, page_number - half)
    except (ValueError, TypeError):
        return 1


@register.filter(name='calculate_end')
def calculate_end(page_number, args):
    """计算结束页码"""
    try:
        return min(page_number + args[0], args[1])
    except (ValueError, TypeError):
        return page_number
